package com.magima.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.text.TextUtils;
import android.telephony.TelephonyManager;

public class MobileContactUtil {
	/** 获取库Phon表字段 **/
	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };

	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;

	/** 头像ID **/
	private static final int PHONES_PHOTO_ID_INDEX = 2;

	/** 联系人的ID **/
	private static final int PHONES_CONTACT_ID_INDEX = 3;
	
	public static final String NAME_KEY = "name";
	public static final String NUMBER_KEY = "number";
	public static final String CONTACTID_KEY = "contact_id";
	public static final String PHOTO_KEY = "photo";
	public static final String PHOTO_URL_KEY = "photo_url";
	public static final String EMAIL_KEY = "email";
	
	private static String mobileNumberFilter(String number){
		number = number.replace(" ", "");
		number = number.replace("-", "");
		number = number.replace("+", "");
		
		if(number.startsWith("86")){
			number = number.replaceFirst("86", "");
		}
		if(number.startsWith("086")){
			number = number.replaceFirst("086", "");
		}
		if(number.startsWith("0086")){
			number = number.replaceFirst("0086", "");
		}
		if(number.startsWith("17951")){
			number = number.replaceFirst("17951", "");
		}
		if(number.startsWith("12593")){
			number = number.replaceFirst("12593", "");
		}
		
		String pattern = "[1][358]{1}[0-9]{9}";
		if (TextUtils.isEmpty(number) || !number.matches(pattern))
			return null;
		else
			return number;
	}
	
	/** 得到手机通讯录联系人信息 **/
	public static List<Map<String, Object>> getPhoneContacts(Context context,List<Map<String, Object>> listContact) {
		ContentResolver resolver = context.getContentResolver();

		// 获取手机联系人
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);
		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {
				Map<String, Object> map = new HashMap<String, Object>();
				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				phoneNumber = mobileNumberFilter(phoneNumber);
				if(phoneNumber == null)
					continue;

				// 得到联系人名称
				String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
				
				// 得到联系人ID
				Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

				// 得到联系人头像ID
				Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);

				// 得到联系人头像Bitamp
				Bitmap contactPhoto = null;

				// photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
				if (photoid > 0) {
					Uri uri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI, contactid);
					InputStream input = ContactsContract.Contacts
							.openContactPhotoInputStream(resolver, uri);
					contactPhoto = BitmapFactory.decodeStream(input);
					map.put(PHOTO_URL_KEY, uri.toString());
				}
				
				map.put(NAME_KEY, contactName);
				map.put(NUMBER_KEY, phoneNumber);
				map.put(PHOTO_KEY, contactPhoto);
				map.put(CONTACTID_KEY, contactid);
				
				Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
		                null,
		                ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactid, null, null);
				int emailIndex = -1;
				if(emailCursor.getCount() > 0){
					emailIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
				}
				if(emailCursor.moveToFirst()){
                    do {
                        String email = emailCursor.getString(emailIndex);
                        map.put(EMAIL_KEY, email);
                        listContact.add(map);
                        //复制一份
                        map = new HashMap<String, Object>();
                        map.put(NAME_KEY, contactName);
                        map.put(NUMBER_KEY, phoneNumber);
                        map.put(PHOTO_KEY, contactPhoto);
                        map.put(CONTACTID_KEY, contactid);
                    } while ( emailCursor.moveToNext() );
				} else {
                    listContact.add(map);
                }
		        emailCursor.close();
			}
			try {
				phoneCursor.close();
			} catch (Exception e){
				
			}
		}
		
		return listContact;
	}

	/** 得到手机SIM卡联系人人信息 **/
	public static List<Map<String, Object>> getSIMContacts(Context context,List<Map<String, Object>> listContact) {
		try {
		ContentResolver resolver = context.getContentResolver();
		// 获取Sims卡联系人
		Uri uri = Uri.parse("content://icc/adn");
		Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
				null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {
				Map<String, Object> map = new HashMap<String, Object>();
				// 得到联系人ID
				Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
				
				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				phoneNumber = mobileNumberFilter(phoneNumber);
				if(phoneNumber == null)
					continue;
				
				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);

                map.put(NAME_KEY, contactName);
                map.put(NUMBER_KEY, phoneNumber);
                map.put(PHOTO_KEY, null);
                map.put(CONTACTID_KEY, contactid);

				Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
		                null,
		                ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactid, null, null);
				int emailIndex = -1;
				if(emailCursor.getCount() > 0){
					emailIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
				}
				if(emailCursor.moveToFirst()){
                    do {
                        String email = emailCursor.getString(emailIndex);
                        map.put(EMAIL_KEY, email);
                        listContact.add(map);
                        //复制一份
                        map = new HashMap<String, Object>();
                        map.put(NAME_KEY, contactName);
                        map.put(NUMBER_KEY, phoneNumber);
                        map.put(PHOTO_KEY, null);
                        map.put(CONTACTID_KEY, contactid);
                    } while ( emailCursor.moveToNext() );
				} else {
                    listContact.add(map);
                }
		        emailCursor.close();

			}
			phoneCursor.close();
		}
		} catch ( Exception e ) {
			//如果一个新手机没有sim卡也没有插入过sim卡，可能会报错
		}
		return listContact;
	}
	
	public interface OnGetMobileContactsListener {
		public void onGetMobileContact(List<Map<String,Object>> contactList);
	}
	public static void getMobileContacts(final Context context,
			final OnGetMobileContactsListener listener) {
		final Handler handler = new Handler(context.getMainLooper()){
			@SuppressWarnings("unchecked")
			@Override  
			public void handleMessage(Message msg) {
				if ( listener != null ) {
					listener.onGetMobileContact((List<Map<String, Object>>) msg.obj);
				}
			}
		};
		Thread thread = new Thread(new Runnable(){
			@Override
			public void run() {
				List<Map<String, Object>> listContact = new ArrayList<Map<String, Object>>();
				getPhoneContacts(context,listContact);
				getSIMContacts(context,listContact);
				Message msg = new Message();
				msg.obj = listContact;
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	
	public static boolean isChineseMobileNo(Context context){
		TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);  
		String imsi = telManager.getSubscriberId();
		if(imsi == null) return false;
		if(imsi.startsWith("46000") || imsi.startsWith("46001") || imsi.startsWith("46002") || imsi.startsWith("46003"))
			return true;
		return false;
	}
}
